package com.hxm.demo.newcoder;

import java.util.ArrayList;
import java.util.List;

/**
 * description: add a description
 *
 * @author huangxiaoming
 * @version 1.0.0
 * @date 2023/08/24 17:40:24
 */
public class TestBM8 {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        ListNode listNode = FindKthToTail2(head, 2);
        System.out.println(listNode);
    }

    public static ListNode FindKthToTail1(ListNode pHead, int k) {
        // write code here
        if (pHead == null) {
            return pHead;
        }
        List<ListNode> list = new ArrayList<>();
        while (pHead != null) {
            list.add(pHead);
            pHead = pHead.next;
        }
        if (k > list.size() || k == 0) {
            return null;
        }
        return list.get(list.size() - k);
    }

    public static ListNode FindKthToTail2(ListNode pHead, int k) {
        // write code here
        if (pHead == null) {
            return pHead;
        }
        if (k == 0) {
            return null;
        }
        ListNode fast = pHead;
        ListNode slow = pHead;
        for (int i = 0; i < k; i++) {
            if (fast == null) {
                return null;
            }
            fast = fast.next;
        }
        while (fast != null && slow != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }
}
